<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $table = 'dd_order';
    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $guarded = array();
    /**
     * 生成订单，返回订单价格
     * @param \Illuminate\Http\Request $request
     */
    public static function order (\Illuminate\Http\Request $request) {
        $data = [
            'productid'     => $request->input('productid'), 
            'name'          => $request->input('name'),
            'phone'         => $request->input('phone'),
            'plotid'        => $request->input('plot'),
            'payphone'      => $request->input('payphone'),
        ];
        if ($request->has('cardnumber')) {
            $data['cardnumber']    = $request->input('cardnumber');
        }
        if ($request->has('address')) {
            $data['address']       = $request->input('address');
        }
        $self = new static();
        $yzres = $self->validMsg($data);
        if($yzres['status'] == 0) {
            return $yzres;
        }
        $data['order']  = date("Ymd").time();
        $data['uid']    = session('home')->id;
        $product        = Product::find($data['productid']);
        $plotfav = Plotfav::where('plotid', $data['plotid'])->where("productid", $data['productid'])->first();
        $data['price']  = $product->price;
        $data['pfav']   = $product->pfav;
        $data['plotfav']= $plotfav ? $plotfav->plotfav : 0;
        $data['plotinit']= $plotfav ? $plotfav->plotinit : 0;
        $data['uqrcode']= session('home')->qrcode;
        $data['type']   = $request->input('ptype');
        $data['time']   = time();
        $order = static::create($data);
        if ($request->has('netname')) {
            $netdate['uid'] = $data['uid'];
            $netdate['orderid'] = $order->id;
            $netdate['ptype'] = 2;
            $netdate['name'] = $request->input('netname');
            $netuser = Netuser::create($netdate);
        }
        return [
            'status'    => 1,
            'info'      => $order
        ];
    }
    
    /**
     * 验证信息
     * @param type $data
     * @return type
     */
    public function validMsg($data) {
        if (!Product::hasProduct($data['productid'])) {
            return [
                "status"    => 0, 
                "info"      => '该产品不存在'
            ];
        }
        if (empty($data['name'])) {
            return [
                "status"    => 0,
                "info"      => '装机联系人姓名需要填写'
            ];
        }
        if (empty($data['phone']) || !preg_match("/^1[3587]\d{9}$/",$data['phone'])) {
            return [
                "status"    => 0,
                "info"      => '联系电话请正确填写'
            ];
        }
        if (!Plot::hasPlot($data['plotid'], $data['productid'])) {
            return [
                "status"    => 0,
                "info"      => '该小区业务暂时没有开通'
            ];
        }
        return [
            "status"    => 1,
            "info"      => "验证通过"
        ];
    }
    /**
     * 订单时间
     * @return type
     */
    public function strTime() {
        return date('Y-m-d H:i:s', $this->time);
    }
    /**
     * 付款完成时间
     */
    public function strPayTime() {
        return $this->paytime ? $this->paytime : "付款未完成";
    }
    
    /**
     * 开户/续费操作时间
     */
    public function strAdminTime() {
        return date("Y-m-d H:i:s", $this->admintime);
    }
    
    /**
     * 订单付款状态
     */
    public function strPayStatus() {
        switch ($this->status) {
            case 0:
                return "订单未付款";
                break;
            case 1:
                return "成功付款";
                break;
            case 2:
                return "订单已关闭";
                break;
            case 3:
                return "成功付款-账户已开通";
                break;
            case 4:
                return "成功付款-账户已续费";
                break;
        }
    }
    /**
     * 产品名称
     */
    public function strProductName() {
        $product = Product::select('name')->find($this->productid);
        return $product ? $product->name : "";
    }
    
   /**
    * 产品类型
    */
    public function strProductType() {
        switch($this->type) {
            case 1:
                return "新装";
                break;
            case 2:
                return "续费";
                break;
        }
    }
    /**
     * 
     * @return type
     */
    public function strPayPhone() {
        return $this->payphone ? $this->payphone : "自付款";
    }
    
    /**
     * 获取用户openid
     */
    public function strGetOpenId() {
        $user = User::find($this->uid);
        return $user->openid;
    }
	/**
	* 获取用户信息
	*/
	public function strGetUser() {
		$user = User::find($this->uid);
		return $user;
	}
	/**
	* 获取产品商品
	*/
	public function strProduct() {
		$product = Product::find($this->productid);
		if($this->type==1) {
			$type = "新入网";
		} elseif($this->type==2) {
			$type = "续费";
		}
		return $product->name.' - '.$type;
	}
    /**
     * 装机小区
     */
    public function strPlot() {
        $plot = Plot::find($this->plotid);
        return $plot ? $plot->name : "未知小区";
    }
    /**
     * 用户上网帐号
     */
    public function strNetUser() {
        $netusers = Netuser::where('orderid', $this->id)->first();
        if (!count($netusers)) {
            return "暂无上网帐号";
        }
//        $accs = [];
//        foreach ($netusers as $val) {
//            $accs[] = $val->name." / ".$val->password;
//        }
        if ($netusers->password) {
            return $netusers->name." / ".$netusers->password;
        } else {
            return $netusers->name;
        }
    }
    /**
     * 订单状态
     * @return string
     */
    public function strStatus($type=1) {
        if($type == 1) {
            switch ($this->status) {
                case 0:
                    $status = "<kbd>未付款</kbd>";
                    break;
                case 1:
                    $status = "<kbd>付款完成</kbd>";
                    break;
                case 2:
                    $status = "<kbd>订单已关闭</kbd>";
                    break;
                case 3:
                    $status = "<kbd>已开户</kbd>";
                    break;
                case 4:
                    $status = "<kbd>已续费</kbd>";
                    break;
                default :
                    $status = "<kbd>未知状态</kbd>";
                    break;
            }
        } else {
            switch ($this->status) {
                case 0:
                    $status = "<kbd class='text-white bg-danger'>未付款</kbd>";
                    break;
                case 1:
                    $status = "<kbd class='text-white'>付款完成</kbd>";
                    break;
                case 2:
                    $status = "<kbd class='text-white bg-danger'>订单已关闭</kbd>";
                    break;
                case 3:
                    $status = "<kbd class='text-white'>已开户</kbd>";
                    break;
                case 4:
                    $status = "<kbd class='text-white'>已续费</kbd>";
                    break;
                default :
                    $status = "<kbd class='text-white bg-info'>未知状态</kbd>";
                    break;
            }
        }
        
        return $status;
    }
    
    /**
     * 获取上网帐号
     */
    public function netUsers() {
        $users = Netuser::where("ptype", 1)->where('uid', $this->uid)->get();
        if(count($users)) {
            return $users;
        }
        return "";
    }
    /**
     * 获取订单帐号昵称
     */
    public function strNickname() {
        $user = User::find($this->uid);
        return $user ? $user->nickname : "";
    }
    
    /**
     * 获取价格
     */
    public function strPrice() {
        return number_format($this->orderPrice(), 2);
    }
    /**
     * 获取用户身份信息
     */
    public function strIdCard() {
        $user = User::find($this->uid);
        if ($user->name && $user->cardnumber) {
            return "身份证姓名：　".$user->name."<br>身份证号码：　".$user->cardnumber;
        }
//        if ($user->idfront && $user->idback) {
//            return "<img src='".asset($user->idfront)."' width='200px'><img src='".asset($user->idback)."' width='200px' style='margin-left: 50px;'>";
//        }
        return "没有上传身份证照片";
    }
    /**
     * 产品类型
     */
    public function strPtype() {
        $ptype = \Illuminate\Support\Facades\Config::get('global.site.ptype');
        return $ptype[$this->type] ? $ptype[$this->type] : "";
    }
    
    /**
     * 支付金额
     */
    public function orderPrice() {
        if (($this->price - $this->pfav - $this->plotfav - $this->adminmod + $this->plotinit) < 0 || ($this->price - $this->pfav - $this->plotfav - $this->adminmod + $this->plotinit) == 0) {
			$price = $this->price;
		} else {
			$price = $this->price - $this->pfav - $this->plotfav - $this->adminmod + $this->plotinit;
		}
        return $price;
    }
    
    /**
     * 获取用户微信昵称
     */
    public function wxNickName() {
        $user = User::find($this->uid);
        if ($user) {
            return $user->nickname;
        } else {
            return "";
        }
    }
    
    /**
     * 获取小区装维师傅
     */
    public function strPlotIper() {
        $pips = Iperplot::where('plotid', $this->plotid)
                ->leftJoin('dd_instperson', 'dd_iperplot.iperid', '=', 'dd_instperson.id')
                ->get();
        if ($pips && count($pips)) {
            $options = "";
            foreach ($pips as $val) {
                $options .= "<option value='".$val->iperid."'>".$val->name."</option>";
            }
        } else {
            $options = "<option value=''>该小区暂时没有安排装维</option>";
        }
        return $options;
    }
    /**
     * 查询订单金额
     */
    public function strTotalMoney($orders) {
        $ttmoney = 0;
        foreach ($orders as $val) {
            $ttmoney += $val->orderPrice();
        }
        return number_format($ttmoney,2);
    }
}
